package com.kingmed.kmss.common.utils.kingmed;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author rain
 * @date 2023/5/15 12:17
 */
public final class HttpTookit {

    private static Log log = LogFactory.getLog(HttpTookit.class);

    private static final int TIMEOUT = 20 * 60 * 1000;

    public static String doGet(String serverUrl, Map<String, String> headers) {

        try {
            return HttpRequest.get(serverUrl).timeout(TIMEOUT).addHeaders(headers).execute().body();
        } catch (Exception ex) {
            log.error("doGet Exception url:" + serverUrl, ex);
        }
        return null;
    }

    public static String doPut(String serverUrl, Map<String, String> headers) {
        try {
            return HttpRequest.put(serverUrl).timeout(TIMEOUT).addHeaders(headers).execute().body();
        } catch (Exception ex) {
            log.error("doPut Exception url:" + serverUrl, ex);
        }
        return null;
    }

    public static String doDelete(String serverUrl, Map<String, String> headers) {
        try {
            return HttpRequest.delete(serverUrl).timeout(TIMEOUT).addHeaders(headers).execute().body();
        } catch (Exception ex) {
            log.error("doDelete Exception url:" + serverUrl, ex);
        }
        return null;
    }

    public static String doPost(String serverUrl, String params, Map<String, String> headers) {
        try {
            return HttpRequest.post(serverUrl).timeout(TIMEOUT).addHeaders(headers).body(params, "application/json;charset=UTF-8").execute().body();
        } catch (Exception ex) {
            log.error("doPost Exception url:" + serverUrl, ex);
        }
        return null;
    }

    public static String doPost(String serverUrl, Map<String, Object> formMap, Map<String, String> headers) {
        try {
            return HttpRequest.post(serverUrl).timeout(TIMEOUT).addHeaders(headers).form(formMap).execute().body();
        } catch (Exception ex) {
            log.error("doPost Exception url:" + serverUrl, ex);
        }
        return null;
    }

    public static String doPost(String serverUrl, Map<String, String> headers) {
        try {
            return HttpRequest.post(serverUrl).timeout(TIMEOUT).addHeaders(headers).execute().body();
        } catch (Exception ex) {
            log.error("doPost Exception url:" + serverUrl, ex);
        }
        return null;
    }


    public static HttpResponse doPostForm(String serverUrl, Map<String, Object> formMap) {
        try {
            return HttpRequest.post(serverUrl).timeout(TIMEOUT).contentType("application/x-www-form-urlencoded; charset=utf-8").form(formMap).execute();
        } catch (Exception ex) {
            log.error("doPost Exception url:" + serverUrl, ex);
        }
        return null;
    }

    public static String doPostGetBody(String serverUrl, Map<String, Object> formMap) {

        HttpPost httpPost = new HttpPost(serverUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
        httpPost.setConfig(requestConfig);

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 设置提交方式
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            // 添加参数
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            if (formMap.size() != 0) {
                // 将params中的key存在set集合中，通过迭代器取出所有的key，再获取每一个键对应的值
                if (formMap != null) {
                    for (String key : formMap.keySet()) {
                        nameValuePairs.add(new BasicNameValuePair(key, formMap.get(key).toString()));
                    }
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            // 执行http请求
            CloseableHttpClient client = HttpClients.custom().build();
            response = client.execute(httpPost, HttpClientContext.create());
            Header location = response.getFirstHeader("Location");
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
//			String tgt = response.getFirstHeader("Location").getValue();
//			log.info("tgt:" + tgt);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPostGetHeader(String serverUrl, Map<String, Object> formMap, String hearder) {

        HttpPost httpPost = new HttpPost(serverUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
        httpPost.setConfig(requestConfig);

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 设置提交方式
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            // 添加参数
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            if (formMap.size() != 0) {
                // 将params中的key存在set集合中，通过迭代器取出所有的key，再获取每一个键对应的值
                if (formMap != null) {
                    for (String key : formMap.keySet()) {
                        nameValuePairs.add(new BasicNameValuePair(key, formMap.get(key).toString()));
                    }
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            // 执行http请求
            CloseableHttpClient client = HttpClients.custom().build();
            response = client.execute(httpPost, HttpClientContext.create());
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("resultString:" + resultString);

            Header location = response.getFirstHeader(hearder);
            if (location != null) {
                return location.getValue();
            } else {
                return null;
            }
//			String tgt = response.getFirstHeader("Location").getValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

}
